<?php

namespace Home\Controller;
use User\Api\UserApi;
use Home\Model\MemberResourceModel;

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class UserController extends HomeController
{
    private $user;  // 当前用户数据
    protected function _initialize()
    {
        parent::_initialize();
        if (!C('USER_ALLOW_REGISTER')) {
            $this->error('注册已关闭');
        }
      
        $this->user = session('user_auth');
        # 更新用户动态数据
        $this->user['score'] = D('member')->where(array('uid'=>$this->user['uid']))->getField('score');
        # END-更新用户动态数据

        if($this->user){
            $this->assign('user', $this->user);
        }
        $where['id'] = UID;
        $result = M('ucenter_member')->where($where)->select();
       // var_dump($result[0]['level']);
        $this->assign('result', $result);
    }
    /* 用户中心首页 */
    public function index()
    {
        if (!UID) {
//	        die('登录失败!fail');
            $this->redirect('User/login');
        }
      
//        die('登录成功!cuess');
//        var_dump($_SESSION);
        $this->display('User/center');
    }

    /**
     * 注册页面
     * @param string $username
     * @param string $mobile
     * @param string $password
     * @param string $repassword
     * @param string $email
     * @param string $verify
     */
    public function register()
    {
        $pid = I('get.pid');	// 分销父级id

        //if (is_numeric(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger'))){
        if(false){
            $wechatAuthArr = session('wechatAuthArr');

            # 获取微信数据
            if ($wechatAuthArr) {
                $nickname = $username = $data['nickname'] = $wechatAuthArr['nickname'];
                $data['sex'] = $wechatAuthArr['sex'];
                $data['headimgurl'] = $wechatAuthArr['headimgurl'];
            }else{
                $this->error('注册方式异常!');
            }
            # END-获取微信数据

            /* 调用注册接口注册用户 */
            $User = new UserApi;
            $uid = $User->register($username, DEFAULT_PASSWORD, $email, $mobile, $pid);
            $data = array(); // member注册数据
            $data['uid'] = $uid;
            $data['nickname'] = $nickname;
            $data['status'] = 1;
            //var_dump($uid);
            //die;
            if ($uid > 0) { //注册成功
                D('Member')->add($data); // 添加注册数据
                //TODO: 发送验证邮件
                action_log('user_register', 'member', $uid, $uid, array('score' => 100)); // 用户增加积分
                if ($pid) {
                    action_log('user_register_recommend', 'member', $uid, $pid, array('score' => 20)); // 推荐人增加积分
                    /*                    $ppid = M('UcenterMember')->where(array('id'=>$pid))->getField('pid');
                                        if($ppid){
                                            action_log('user_register', 'member', $uid, $ppid, array('score'=>1)); // 推荐人父级增加积分
                                        }*/
                }
                # 获取code对应的用户id, 且自动登录
                if ($uid && D('Member')->login($uid)) { // 自动登录
                    # 插入授权code
                    if (@$wechatAuthArr['openid']) {
                        $data = array();
                        $data['uid'] = $uid;
                        $data['auth_code'] = $wechatAuthArr['openid'];
                        $data['auth_nickname'] = $wechatAuthArr['nickname'];
                        M('MemberAuth')->add($data, null, true);
                        redirect(WECHAT_ATTENTION);
                    }
                    # END-插入授权code
                    $this->success('注册成功！', U('User/index'));
                }else{
                    $this->error('注册失败！'.D('Member')->getError(), U('Index/index'));
//                    D('Member')->del($uid);   // 重名情况是不能删除的
                }
                # END-获取code对应的用户id, 且自动登录

            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        }else{
            $username = I('username');
            $mobile = I('mobile');
            $password = I('password', DEFAULT_PASSWORD);
            $repassword = I('repassword', DEFAULT_PASSWORD);
            $email = I('email');
            $nickname = I('nickname');
            $verify = I('verify');
            $recommendMobile = I('recommend_mobile');

            if (IS_POST) { //注册用户
                /* 检测验证码 */
                if (session('smsVerify') != $verify) {
                    $this->error('验证码输入错误！');
                }

                /* 检测密码 */
                if ($password != $repassword) {
                    $this->error('密码和重复密码不一致！');
                }

                // 用户名不存在则使用手机号作为用户名
                if (empty($username)) {
                    $username = $mobile;
                }

                # 获取上级id
                if(!$pid){
                    if(is_numeric($recommendMobile) && strlen($recommendMobile) == 11){
                        $pid = M("UcenterMember")->where(array('mobile'=>$recommendMobile))->getField('id');
                        if(!$pid && $pid=0){    // 不存在时, 赋值pid
                            $this ->error('推荐人不存在');
                        }
                    }else if($recommendMobile){
                        $this->error('请核对推荐人11位手机号码！');
                    }
                }

                # END-获取上级id

                /* 调用注册接口注册用户 */
                $User = new UserApi;
                $uid = $User->register($username, $password, $email, $mobile, $pid);
                $data = array(); // member注册数据
                $data['uid'] = $uid;
                $data['nickname'] = $nickname;

                if ($uid > 0) { //注册成功
                    M('Member')->add($data); // 添加注册数据
                    //TODO: 发送验证邮件
                    action_log('user_register', 'member', $uid, $uid, array('score'=>100));     // 用户增加积分
                    if($pid){
                        action_log('user_register_recommend', 'member', $uid, $pid, array('score'=>20)); // 推荐人增加积分
                        /*                    $ppid = M('UcenterMember')->where(array('id'=>$pid))->getField('pid');
                                            if($ppid){
                                                action_log('user_register', 'member', $uid, $ppid, array('score'=>1)); // 推荐人父级增加积分
                                            }*/
                    }
                    if (is_numeric(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger'))){
                        # 获取code对应的用户id, 且自动登录
                        if($uid && D('Member')->login($uid)){	// 自动登录
                            $this->redirect('User/index');
                        }
                        # END-获取code对应的用户id, 且自动登录
                    }
                    if($uid){
                        $this->success('注册成功！', U('User/index'));
                    }else{
                        $this->error('注册失败！', U('Index/index'));
                    }
                } else { //注册失败，显示错误信息
                    $this->error($this->showRegError($uid));
                }
            } else { //显示注册表单
                # END-获取微信数据
                $this->display();
            }
        }

    }

    /**
     * 登录操作
     */
    public function login()
    {
        if (IS_POST) {
            $username = I("post.username");
            $password = I("post.password");
            //var_dump($username,$password);
            if (empty($username) || empty($password)) {
                $this->error('账户或密码不能为空!');
            }
            /* 调用UC登录接口登录 */
            $User = new UserApi;
            $uid = $User->login($username, $password);


            if (0 < $uid) { //UC登录成功
                /* 登录用户 */
                $Member = D('Member');
                if ($Member->login($uid)) { //登录用户
                    //TODO:跳转到登录前页面
                    //$this->success('登录成功！', U('Index/index'),true);
                    # 绑定用户id
                    //var_dump(session('wechatAuthArr'));
                    $data = array();
                    $data['uid'] = $uid;
                    $wechatAuthArr = session('wechatAuthArr');
                    $where = array();
                    $where['auth_code'] = $wechatAuthArr['openid'];
                    M('MemberAuth')->where($where)->save($data);
                    //var_dump(M()->getLastSql());
                    //die;
                    # END-绑定用户id


                    if($_SESSION['url']){
                        $go = session("url");//$_SESSION['url'];
                        session("url", null);//$_SESSION['url'] = '';
                        header("Location:".$go);
                    }
                    $this->redirect('User/index');
                } else {
                    $this->error($Member->getError());
                }

            } else { //登录失败
                switch ($uid) {
                    case -1:
                        $error = '用户不存在或被禁用！';
                        break; //系统级别禁用
                    case -2:
                        $error = '密码错误！';
                        break;
                    default:
                        $error = '未知错误！';
                        break; // 0-接口参数错误（调试阶段使用）
                }
                $this->error($error);
            }
        } else {
            $this->display();
        }
    }

    /* 退出登录 */
    public function logout()
    {
        if (is_login()) {
            D('Member')->logout();
            $this->success('退出成功！', U('Index/index'));
        } else {
            $this->success('退出失败！', U('Index/index'));
        }
    }

    /**
     * 短信验证码
     */
    public function smsVerify()
    {
        $result = array('error' => 0, 'msg' => ''); // 返回数据
        $mobile = I('mobile');
        //var_dump($mobile);
        if (empty($mobile)) {
            $result['error'] = -1;
            $result['msg'] = '您的手机号不存在!!';
            die(json_encode($result));
        }
        $smsVerify = substr(time(), -4);
        session('smsVerify', $smsVerify);
        $result['code'] = $smsVerify;

        // $resp = realSendSMS($sender, $smsTemp['sms_sign'], $smsParam, $smsTemp['sms_tpl_code']);
        $message = mb_convert_encoding("【优才圈】您的短信验证码是:".$smsVerify.",如非本人操作，请忽略。","gb2312","utf-8");
        $url = 'http://42.96.248.183:8080/sendsms.php?userid=102471&username=youcai&passwordMd5='.md5('pyoucai')
            .'&mobile='.$mobile.'&message='.$message.'';
        $file_contents = file_get_contents($url);
        //var_dump($file_contents);
        if ($file_contents > 0) {
            $result['msg'] = '获取短信验证码成功!';
        } else {
            $result['msg'] = '获取短信验证码失败!';
        }
        die(json_encode($result));
    }

    /* 验证码，用于登录和注册 */
    public function verify()
    {
        $verify = new \Think\Verify();
        $verify->entry(1);
    }


    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function profile()
    {
        if (IS_POST) {
            //获取参数
            $uid = UID;
            $password = I('post.oldpassword');
            $repassword = I('post.repassword');
            $data['password'] = I('post.password');
            empty($password) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');

            if ($data['password'] !== $repassword) {
                $this->error('您输入的新密码与确认密码不一致');
            }

            $Api = new UserApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if ($res['status']) {
                $this->success('修改密码成功！', 'User/index');
            } else {
                $this->error($res['info']);
            }
        } else {
            $this->assign('title', '账户设置');
            $this->display();
        }
    }

    /**
     * 个人信息
     */
    public function detail(){
        $this->assign('title', '个人信息');
        $this->display();
    }

    /**
     * 个人信息
     */
    public function detailEdit(){
        if(IS_POST){
            $uid = UID;
            //$password = I('post.oldpassword');
            //$password = null;
            //var_dump($password);exit;
            $data = array();
            $data['nickname'] = I('nickname');

            if(!empty($_FILES['headimgurl']['name'])){
                $data['headimgurl'] =  $this->_upload('headimgurl');
                $data['headimgurl'] = $data['headimgurl'] ? urlAddDomain($data['headimgurl']) : '';
            }
            D('Member')->where(array('uid'=>$uid))->save($data); // 添加注册数据
            unset($data['nickname']);

            $data['id'] = $uid;     // 自动验证时, 用于排除自身
            $data['mobile'] = I('mobile');
            $data['email'] = I('email');
            //$data['username'] = I('username');
            $Api = new UserApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if($res){
                D('Member')->login($uid);
                $this->success('修改信息成功！', 'User/index');
            }
            $this->error('修改信息失败！');
        }
        $this->assign('title', '个人信息-编辑');
        $this->display();
    }

    /**
     * 我的收藏
     */
    public function collect(){
//        $_SESSION = array();
        $prefix = C('DB_PREFIX');
        $collectList = M()
            ->field('d.*,d.id as did,d.create_time as time,p.*,p.id as pid')
            ->table($prefix.'collection as d')
            ->join ($prefix.'active as p on d.active_id = p.id')
            ->where("d.user_id=".UID)
            ->select();

        $articleCollect = M()
            ->field('d.*,p.*,p.id as pid')
            ->table($prefix.'member_resource as d')
            ->join ($prefix.'document as p on d.resource_id = p.id')
            ->where("d.uid=".UID)
            ->select();

        $res = [];
        $sort_time = [];
        foreach ($collectList as $k=>$v){
            $v["flag"] = 1;
            $res[] = $v;
            $sort_time[] = $v["time"];
        }
        foreach ($articleCollect as $k=>$v){
            $v["flag"] = 2;
            $res[] = $v;
            $sort_time[] = $v["time"];
        }
        array_multisort($sort_time, SORT_DESC, $res);

        foreach ($collectList as $k => $v) {
            $v["order_count"] = M("order")->where(["active_id"=>$v["pid"]])->count();
            $collectList[$k] = $v;
        }
        //var_dump($articleCollect);
        $this->assign('res', $res);
        $this->assign('collectList', $collectList);
        $this->assign('articleCollect', $articleCollect);
        $this->assign('title', '我的收藏');
        $this->display();
    }

    /**
     * 我的消息
     */
    public function message(){
//        $_SESSION = array();
        $list = M('ActionLog')->where(array('user_id'=>UID))->group('record_id')->order('create_time desc')->limit(10)->select();
        FPC($list);
        $this->assign('list', $list);
        $this->assign('title', '我的消息');
        $this->display();
    }

    /**
     * 我的问答
     */
    public function faq(){
        $where['ask.status'] = 1;

        $order = "id desc";
        switch(I('type')){
            case 'answer':
                $where['a.status'] = 1;
                $where['a.uid'] = UID;
                break;
            default:
                $where['ask.uid'] = UID;
        }
        $prefix = C('DB_PREFIX');
        $askList = M()
            ->field('ask.*, a.content as acontent, a.id as aid, a.agree ')
            ->table($prefix.'ask as ask')
            ->join($prefix."answer as a ON ask.id=a.ask_id",'LEFT')
            ->where($where)->order($order)->limit(30)->select();
        //var_dump($askList);
        $this->assign('askList', $askList);
        $this->assign('title', '我的问答');
        $this->display();
    }

    /**
     * 分销页面
     */
    public function distribution(){
        $this->display();
    }


    /**
     * @desc  下级收益
     */
    public function sonIncome(){
        $uid = UID;
        $all_member = M('UcenterMember')->field('id,pid,username')->select();
        $this ->assign('username',M('UcenterMember')->getFieldById($uid,'username'));
        $info = $this ->_searchList($all_member,$uid);
        $this ->assign('info' , $info);
        //var_dump($info);
        FPC($info);
        $this->assign('title', '我的下级');
        $this ->display();
    }

    /**
     * @desc 取出格式化的子孙栏目
     * @param number $cid
     */
    private function _searchList($arr , $id = 0) {

        $childs = $this->getChild($arr,$id);
        if(!empty($childs)){
            foreach($childs as $k =>$v){
                $childs[$k]['son'] = $this ->_searchList($arr,$v['id']);
            }
        }
        return $childs;
    }

    /**
     * @desc 递归取出所有子孙节点
     * @return 返回结构信息
     */
    public function getChild($arr , $id){
        $childs = array();
        foreach ($arr as $k=> $v) {
            if ($v['pid'] == $id){
//                $arr[$k]['income'] = M('MemberIncome')->where('income_user = '.$v['id'])->sum('money');
                $arr[$k]['income'] = M('ActionLog')->where('user_id = '.$v['id'])->sum('score');
                if(empty($arr[$k]['income']))
                    $arr[$k]['income'] = 0;
                $childs[] = $arr[$k];
            }
        }
        return $childs;
    }

    /**
     * @desc   下级订单
     */
    public function sonOrder($isScore=false){
        $uid = UID;
        $sons = $this ->getSonTree($uid);

        $where = array();
        $where['user_id'] = array(0=>'in');
        $where['al.status']= 1;
        if(count($sons) == 1){
            $where['user_id'][1] = $sons[0]['id'];
        }elseif(count($sons) > 1){
            foreach($sons as $v){
                $where['user_id'][1] .= $v['id'].',';
            }
        }
        $where['user_id'][1] && $where['user_id'][1] = trim($where['user_id'][1], ',');
//        if(!$isScore){
//            $where['al.score'] = array('NEQ', 0);
//        }else{
//            $where['al.score'] = array('EQ', 0);
//        }

        $where['al.action_id'] = M('Action')->where(array('name'=>array('in', 'read_category,read_article')))->getField('id', true);
        $where['al.action_id'] && $where['al.action_id'] = array('in', implode($where['al.action_id'], ','));

        if(I('type')=='score'){
            $order = "al.score desc, al.create_time desc";
        }else{
            $order = "al.create_time desc";
        }

        if($sons){
//            $list = M('ActionLog')->where($where)->order('create_time desc')->limit(20)->select();
            $prefix = C('DB_PREFIX');
            $list = M()
                ->field('um.username,um.mobile, al.*, m.nickname')
                ->table($prefix.'action_log as al')
                ->join ($prefix.'ucenter_member as um on um.id =al.user_id')
                ->join ($prefix.'member as m on m.uid =al.user_id')
                ->where($where)
                ->order($order)
                ->limit(20)
                ->select();
            $tempList = array();
            foreach($list as &$arr){
                $arr['modelName'] = $arr['model']=='article' ? 'document' : $arr['model'];
                $arr['title'] = M($arr['modelName'])->where(array('id'=>$arr['record_id']))->getField('title');
                if($arr['model']=='article'){
                    $arr['url'] = U('article/detail', array('id'=>$arr['record_id']));
                }elseif($arr['model']=='category'){
                    $arr['url'] = U('category/lists', array('cateid'=>$arr['record_id']));
                }else{
                    $arr['url'] = 'javascript:;';
                }
            }
            unset($arr);
            foreach($list as $arr){
                $tempList[$arr['user_id']]['info'] = $arr;
                $tempList[$arr['user_id']]['list'][] = $arr;
            }
            $list = $tempList;
        }else
            $list = array();

        $this ->assign('list' , $list);
        if(!$isScore){
            $this->assign('title', '下级浏览记录');
            $this ->display();
        }
    }

    /**
     * @desc  获取自己的下级会员
     * @param int $my_id
     * @return array
     */
    public function getSonTree($my_id){
        $all_grade =  M('UcenterMember')->field('id,pid,username')->select();
        return $this ->getTree($all_grade , $my_id);
    }

    /**
     * @desc 取出所有的子孙栏目
     * @param arary $arr
     * @param number $id
     */
    public function getTree($arr,$id=0){
        $tree=array();
        foreach($arr as $v){
            if($v['pid']==$id){
                $tree[]=$v;
                $tree=array_merge($tree,$this->getTree($arr,$v['id']));
            }
        }
        return $tree;
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0)
    {
        switch ($code) {
            case -1:
                $error = '用户名长度必须在16个字符以内！';
                break;
            case -2:
                $error = '用户名被禁止注册！';
                break;
            case -3:
                $error = '用户名被占用！';
                break;
            case -4:
                $error = '密码长度必须在6-30个字符之间！';
                break;
            case -5:
                $error = '邮箱格式不正确！';
                break;
            case -6:
                $error = '邮箱长度必须在1-32个字符之间！';
                break;
            case -7:
                $error = '邮箱被禁止注册！';
                break;
            case -8:
                $error = '邮箱被占用！';
                break;
            case -9:
                $error = '手机格式不正确！';
                break;
            case -10:
                $error = '手机被禁止注册！';
                break;
            case -11:
                $error = '手机号被占用！';
                break;
            default:
                $error = '未知错误';
        }
        return $error;
    }


    public function invite()
    {
	    $data = I();
	    $data['pid'] = I('pid', UID);
        $url = U('user/register', $data, null, true);
        // echo $url;
        $imageCodel = '<img src="http://qr.liantu.com/api.php?&w=150&text=' . $url. '"/>';
        $this->assign('imageUrl', $url);
        $this->assign('imageCode', $imageCodel);
        $this->assign('title', '邀请码邀请');
        $this->display();
    }

    public function help()
    {
        $this->display();
    }
    public function vip()
    {
        $this->assign('title', '会员升级');
        $this->display();
    }
    public function order()
    {

        if( I('pay_status')!=='' ){
            $where['pay_status'] = I('pay_status');
        }
        if( I('type')!=='' ){
            $where['type'] = I('type');
        }
        $where['user_id'] = $this->user['uid'];

        $this->assign('title', '我的订单');
        $result = M('order')->where($where)->order('add_time desc')->select();
        //var_dump($result);
        $this->assign('result', $result); 
        $this->display();


    }


}
